/*
 *	add element view
 *  -----------------------------------------------------------------------------------------------------------
 */

site.view('edit-element-modal', {
	
	modal: true,
	elementId: 'edit-element-modal',
	
	elements: {
		finder: {
			field: '#find',
			button: '#find_button'
		},
		
		formFields: {
			title: '#title',
			description: '#description',
			field: '#project_field',
			link: '#link'
		},
		
		uploadButton: '#upload_icon', 
		
		iconContainer: '#icon_container',
		selectedIcon: '#selected_icon'
	},
	
	onLoad: function(settings) {
		
		if(!this.loaded) {
			var that = this;	
		
			this.request({
				url: '/desktop/edit',
				dataType: 'json',
				type: "post",
				data: settings.data,
				success: function(data) {
					
					if(!data.success) return;

					that.projectViewHtml = that.createElement('div');
					that.projectViewHtml.setAttribute('id', that.elementId);
					that.projectViewHtml.setAttribute('style', 'display: none;');	
					that.projectViewHtml.innerHTML = data.content;
					
					that.startAll(that.projectViewHtml, that.elements, settings || {});
				}
			});
		}
	},
	
	onUnload: function() {
		this.stopAll();
	}
})


.module('add_item_manager', function(context) {
	
	var query = context.query,
		TabControl = context.require('Tabs').TabControl,
	
		container,
		overlay_message,
		
		toggleIconSelect,
		selectedIcon,
		selectedIconData = { id: 0, src: '', changed: false},
		iconContainer,
		
		titleField,
		descriptionField,
		linkField,
		
		onEdit,
		iconSelectControl = new TabControl();
	
	return {
		
		init: function(addElementViewHtml, elements, settings) {

			onEdit = typeof(settings.onEdit) === 'function' ? settings.onEdit : function(){};
			
			container = query(addElementViewHtml);
			query('body').append(addElementViewHtml);
			selectedIcon = query('#selected_icon');
			selectedIconData.src = selectedIcon.prop('src'); 
			
			icon_container = query(elements.iconContainer);
			
			titleField = query(elements.formFields.title);	
			fieldField = query(elements.formFields.field);
			descriptionField = query(elements.formFields.description);	
			linkField = query(elements.formFields.link);	
				
			container.fadeIn('normal');
			
			// Icon select control
			iconSelectControl.addTab('upload', query('#btn_upload_icon').click(function() { 
				iconSelectControl.changeTab('upload'); 
				return false;
			}), 
			query('.upload_icon_view'));
			
			iconSelectControl.addTab('find', query('#btn_find_icon').click(function() { 
				iconSelectControl.changeTab('find'); 
				return false;
			}), 
			query('.find_icon_view'));
			
			iconSelectControl.changeTab('find');
			
			// Overlay
			var that = context.query(this);    
			overlay_message = context.query('#edit-element-msg-prompt').overlay({
				top: 150,
				mask: {color: '#000', loadSpeed: 400, opacity: 0.5},
				closeOnClick: true,
				load: true,
				onClose: function() {
					context.query('#edit-element-msg-prompt').remove();
					context.closeView();
				}
			});
		
			query('#overlay_item_edit').click( function() {


				if(settings.data.type === 'project') {
					
					request_data = {
						id: settings.data.id,
						type: 'project',
						title: titleField.val(),
						description: descriptionField.val(),
						field: fieldField.val(),
						iconData: selectedIconData
					}
					
				} else if (settings.data.type === 'link') {
				
					request_data = {
						id:  settings.data.id,
						type: 'link',
						title: titleField.val(),
						description: descriptionField.val(),
						link: linkField.val(),
						iconData: selectedIconData
					}
					
				}
			
				context.request({	
					url: '/desktop/edit_item',
					dataType: 'json',
					type: "post",
					data: request_data,
					success: function(data) {
						
						if(data.success === true) {
							context.closeView();
							onEdit.call(null, data.data);

							query('#notification_container').notify('create','basic-template', {
								title: data.message,
							});

						} else {
							
							var err_msg = '';
							
							for(var error in data.errors) {
								if(data.errors.hasOwnProperty(error)) {
									err_msg += data.errors[error] + '<br/>';
								}
							}
							
							query('#notification_container').notify('create','error-template', {
								title: data.message,
								text: err_msg
							});
						}
					},
					error: function(err) {
						console.log('add desktop item error: ' + err);
						
						query('#notification_container').notify('create','error-template', {
							title: 'Cannot add item',
							text: 'Item <b>' + request_data.item_title + '</b> cannot be added. Service unavailable.'
						});
					}
				});
			});
			
			context.query('#overlay_item_cancel').click( function() {
				context.closeView();					
			});
		
		},
		
		destroy: function() {
			
			if(overlay_message.overlay().isOpened) {
				overlay_message.overlay().close();
			}
			
			container.html('');
			container.remove();
		},
		
		events: {
		
			iconSelected: function(source, id) {
				
				selectedIconData = {
					id: id,
					src: source,
					changed: true
				};

				selectedIcon.prop('src', source);	
			},
			
			searchQuery: function(query) {
				context.trigger('findIcon', query);
			},
			
			iconsetFound: function(iconList) {
				
				context.trigger('clearIconContainer');
				context.trigger('showIconContainer');

				for(var icon in iconList) {
					if(iconList.hasOwnProperty(icon)) {
						context.trigger('addIconElement', iconList[icon].image);
					}
				}
			}
		}
	};
})

.module('icon_uploader', function(context) {
	
	var fileUploader = context.require('FileUploader'),
	query = context.query, 
	uploadButton,
	uploader;
 
	return {
		
		init: function(addElementViewHtml, elements, settings) {
			
			uploadButton = query(elements.uploadButton);
			
			uploader = fileUploader.create({
				element: uploadButton.get(0),
				action: '/desktop/upload_icon',
				name: 'item_icon',
				allowedExtensions: ['png','ico'],        
				sizeLimit: 150*1024,
				multiple: false,
				onComplete: function(id, fileName, res) {

					if(res.success === true) {
						context.trigger('iconSelected', res.icon_path, res.icon_id);
					}
				}
			});
		},
		
		destroy: function() {
			
		}
	
	};
})

.module('icon_finder', function(context) {
	
	var query = context.query, 
	finder,
	findButton,
	
	onChange = function(eventObj) {
		var text = query(this).val();
		if(text.length > 0) {	
			context.trigger('searchQuery', text);
		}
		
		return false;
	};

	return {
		
		init: function(addElementViewHtml, elements) {
			findButton = query(elements.finder.button);
			finder = query(elements.finder.field);
			findButton.bind('click', onChange);
			finder.bind('change', onChange);
		},
		
		destroy: function() {
			finder.unbind('change', onChange);
		}
	
	};
})

.module('icon_container', function(context) {

	var query = context.query, 
	icon_container;

	return {
		
		init: function(addElementViewHtml, elements) {
			icon_container = query(elements.iconContainer);	
			this.events.clearIconContainer();
		},
		
		destroy: function() {
		},
		
		events: {
		
			addIconElement: function(source) {
				var img = context.createElement('img');
				img.setAttribute('src', source);
				
				query(img).click(function () {
					var source = query(this).prop('src');
					context.trigger('iconSelected', source, 0);
				});
				
				icon_container.append(img);
			},
			
			clearIconContainer: function() {
				icon_container.empty();
			},

			showIconContainer: function() {
				icon_container.slideDown();
			}
		}
	};
})

.module('icon_finder_service', function(context) {
	
	var query = context.query,
	
	backupService = false,

	serviceUrlBak = 'http://www.iconfinder.com/search/',
	request_data_bak = {
		q: '',											// search query
		min: 48,										// min icon size
		max: 64,										// max icon size
		c: 50,											// results per page (only one page visible)
		l: 0,											// licence type
	},
	
	serviceUrlDef = 'http://www.iconfinder.com/json/search/',
	request_data_def = {
		q: '',											// search query
		min: 48,										// min icon size
		max: 128,										// max icon size
		c: 50,											// results per page (only one page visible)
		l: 0,											// licence type
		api_key: '62863a8f2bc9a33f100a75f471c70e64'  	// as skowronkow user
	},

	serviceUrl = backupService ? serviceUrlBak : serviceUrlDef,
	request_data = backupService ? request_data_bak : request_data_def,
	
	onSuccess = function(data) {
		
		if(!backupService) {
			
			var icons = data.searchresults.icons,
			totalResults = data.searchresults.totalResults;
				
			if(totalResults > 0) {
				context.trigger('iconsetFound', icons);
			} else {
				context.trigger('iconsetFound', {});
			}

		} else {
			alert(data);	
		}
		
	};

	return {
		events: {
			
			findIcon: function(search_text) {
				
				if(search_text.length === 0)
					return;
	
				request_data.q = search_text;
					
				if(!backupService) {
					context.request({
						url: serviceUrl,
						data: request_data,
						success: onSuccess,
						error: function(data) { 
							console.log('icon_finder_service error')
						},
						dataType: 'jsonp'
					});
	
				} else {
					context.request({
						url: serviceUrl,
						data: request_data,
						success: onSuccess,
						error: function(data) { 
							console.log(data);
						},
						dataType: 'jsonp'
					});
				}

			}
		}
	}
	
});